//
//  NvTakeVideoViewController.m
//  NvSellerShow
//
//  Created by dx on 17/2/14.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvTakeVideoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "NvsStreamingContext.h"
#import "NvsLiveWindow.h"
#import "ZJSwitch.h"
#import "TakeVideoPreViewController.h"
#import "NvMakeFilmClipModel.h"
#import "UIColor+Hex.h"


@interface NvTakeVideoViewController ()<TakeVideoPreViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UIImageView *guideImageView;
@property (weak, nonatomic) IBOutlet UILabel *guideLabel;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (weak, nonatomic) IBOutlet UIButton *flashBtn;
@property (weak, nonatomic) IBOutlet UIButton *guideBtn;
@property (weak, nonatomic) IBOutlet UIButton *devicePositionChangeBtn;

@property (weak, nonatomic) IBOutlet UIImageView *rotateImageView;
@property (weak, nonatomic) IBOutlet UIButton *recordBtn;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet ZJSwitch *switchBtn;
@property (strong, nonatomic) IBOutlet NvsLiveWindow *liveWindow;
@property (weak, nonatomic) IBOutlet UIButton *camaraLabel;

@end

@implementation NvTakeVideoViewController
{
    NvsStreamingContext *_context;
    unsigned int _currentDeviceIndex;
    BOOL _isNeedRestartPreview;
    BOOL _isRecording;
    BOOL _isflashOn;
    BOOL _enableRotation;//是否允许旋转（注意在视频录制过程中禁止屏幕旋转）
    BOOL _isRotate;
    NvsRational _aspectRatio;
    PHAsset *_videoAsset;
    TakeVideoPreViewController *preViewController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSwitchBtn];
    _sureBtn.hidden = YES;
    _cancelBtn.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    
    if (self.editmode == NvSSVideoCreateScaleVertical) {
        self.guideLabel.text = @"请竖屏拍摄(关闭屏幕方向锁定)";
        if ([[UIDevice currentDevice] orientation]==UIInterfaceOrientationPortrait) {
            _isRotate = true;
            _timeLabel.hidden = NO;
            _recordBtn.hidden = NO;
            _rotateImageView.hidden = YES;
            _guideLabel.hidden = YES;

        } else if ([[UIDevice currentDevice] orientation]==UIInterfaceOrientationLandscapeRight) {
            _isRotate = false;
            _timeLabel.hidden = YES;
            _recordBtn.hidden = YES;
            _rotateImageView.hidden = NO;
            _guideLabel.hidden = NO;
        }else {
            _isRotate = false;
            _timeLabel.hidden = YES;
            _recordBtn.hidden = YES;
            _rotateImageView.hidden = NO;
            _guideLabel.hidden = NO;
        }
    } else {
        self.guideLabel.text = @"请横屏拍摄(关闭屏幕方向锁定)";
        if ([[UIDevice currentDevice] orientation]==UIInterfaceOrientationPortrait)
        {
            _isRotate = false;
            _timeLabel.hidden = YES;
            _recordBtn.hidden = YES;
            _rotateImageView.hidden = NO;
            _guideLabel.hidden = NO;
            
        }
        else if ([[UIDevice currentDevice] orientation]==UIInterfaceOrientationLandscapeRight)
        {
            _isRotate = true;
            _timeLabel.hidden = NO;
            _recordBtn.hidden = NO;
            _rotateImageView.hidden = YES;
            _guideLabel.hidden = YES;
            CGAffineTransform rotation = CGAffineTransformMakeRotation(M_PI_2);
            [_backBtn setTransform:rotation];
            [_flashBtn setTransform:rotation];
            [_guideBtn setTransform:rotation];
            [_switchBtn setTransform:rotation];
            [_rotateImageView setTransform:rotation];
            [_guideLabel setTransform:rotation];
            [_camaraLabel setTransform:rotation];
            [_timeLabel setTransform:rotation];
        }else {
            _isRotate = false;
            _timeLabel.hidden = YES;
            _recordBtn.hidden = YES;
            _rotateImageView.hidden = NO;
            _guideLabel.hidden = NO;
        }
    }

    [self cameraDistrict];
    [self initGesture];
    [self addNotification];   
    
    // Do any additional setup after loading the view.
}

- (void)addNotification {
    __weak __typeof(self)weakSelf = self;
    [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil queue:[[NSOperationQueue alloc] init] usingBlock:^(NSNotification * _Nonnull note) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (_isRecording)
                [weakSelf finishRecord];
            _isNeedRestartPreview = YES;
        });
        
    }];
    [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillEnterForegroundNotification object:nil queue:[[NSOperationQueue alloc] init] usingBlock:^(NSNotification * _Nonnull note) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf ensureStartPreview];
        });
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)initGesture {
    _focusView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    _focusView.layer.borderWidth = 1.0;
    _focusView.layer.borderColor =[UIColor yellowColor].CGColor;
    _focusView.backgroundColor = [UIColor clearColor];
    _focusView.hidden = YES;
    [self.view addSubview:_focusView];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(focusGesture:)];
    [self.view addGestureRecognizer:tapGesture];
    [_context startAutoFocus:self.focusView.center];
    [self.liveWindow addGestureRecognizer:tapGesture];
}

-(void)initSwitchBtn {
    _switchBtn.style = ZJSwitchStyleBorder;
    _switchBtn.knobText = @"引导";
    _switchBtn.knobTextOnColor = [UIColor colorWithHexString:@"59BEE1"];
    _switchBtn.knobTextOffColor = [UIColor blackColor];
    _switchBtn.thumbTintColor = [UIColor whiteColor];
    
    _switchBtn.onTextColor = [UIColor colorWithHexString:@"59BEE1"];
    _switchBtn.onContentViewColor = [UIColor colorWithHexString:@"59BEE1"];
    _switchBtn.offContentViewColor = [UIColor blackColor];
    _switchBtn.on = NO;
    _switchBtn.hidden = YES;
}


- (void)orientChange:(NSNotification *)noti {
    if(!_enableRotation)
        return;
    UIDeviceOrientation  orient = [UIDevice currentDevice].orientation;

    CGAffineTransform rotation;
    if (self.editmode == NvSSVideoCreateScaleVertical) {
        switch (orient)
        {
            case UIDeviceOrientationLandscapeLeft:
                _timeLabel.hidden = YES;
                _recordBtn.hidden = YES;
                _rotateImageView.hidden = NO;
                _guideLabel.hidden = NO;
                
                break;
            case UIDeviceOrientationPortrait:
                _timeLabel.hidden = NO;
                _recordBtn.hidden = NO;
                _rotateImageView.hidden = YES;
                _guideLabel.hidden = YES;
                break;
            case UIDeviceOrientationPortraitUpsideDown:
                _timeLabel.hidden = YES;
                _recordBtn.hidden = YES;
                _rotateImageView.hidden = NO;
                _guideLabel.hidden = NO;
                break;
            case UIDeviceOrientationLandscapeRight:
                _timeLabel.hidden = YES;
                _recordBtn.hidden = YES;
                _rotateImageView.hidden = NO;
                _guideLabel.hidden = NO;
                break;
            case UIDeviceOrientationUnknown:
                
                break;
            default:
                
                break;
        }
    } else {
        switch (orient)
        {
            case UIDeviceOrientationPortrait:
                _timeLabel.hidden = YES;
                _recordBtn.hidden = YES;
                _rotateImageView.hidden = NO;
                _guideLabel.hidden = NO;
                
                [_backBtn setTransform:CGAffineTransformIdentity];
                [_flashBtn setTransform:CGAffineTransformIdentity];
                [_guideBtn setTransform:CGAffineTransformIdentity];
                [_switchBtn setTransform:CGAffineTransformIdentity];
                [_rotateImageView setTransform:CGAffineTransformIdentity];
                [_guideLabel setTransform:CGAffineTransformIdentity];
                [_camaraLabel setTransform:CGAffineTransformIdentity];
                [_timeLabel setTransform:CGAffineTransformIdentity];
                
                break;
            case UIDeviceOrientationLandscapeLeft:
                _timeLabel.hidden = NO;
                _recordBtn.hidden = NO;
                _rotateImageView.hidden = YES;
                _guideLabel.hidden = YES;
                rotation = CGAffineTransformMakeRotation(M_PI_2);
                [_backBtn setTransform:rotation];
                [_flashBtn setTransform:rotation];
                [_guideBtn setTransform:rotation];
                [_switchBtn setTransform:rotation];
                [_rotateImageView setTransform:rotation];
                [_guideLabel setTransform:rotation];
                [_camaraLabel setTransform:rotation];
                [_timeLabel setTransform:rotation];
                break;
            case UIDeviceOrientationPortraitUpsideDown:
                _timeLabel.hidden = YES;
                _recordBtn.hidden = YES;
                _rotateImageView.hidden = NO;
                _guideLabel.hidden = NO;
                
                [_backBtn setTransform:CGAffineTransformIdentity];
                [_flashBtn setTransform:CGAffineTransformIdentity];
                [_guideBtn setTransform:CGAffineTransformIdentity];
                [_switchBtn setTransform:CGAffineTransformIdentity];
                [_rotateImageView setTransform:CGAffineTransformIdentity];
                [_guideLabel setTransform:CGAffineTransformIdentity];
                [_camaraLabel setTransform:CGAffineTransformIdentity];
                [_timeLabel setTransform:CGAffineTransformIdentity];
                break;
            case UIDeviceOrientationLandscapeRight:
                _timeLabel.hidden = YES;
                _recordBtn.hidden = YES;
                _rotateImageView.hidden = NO;
                _guideLabel.hidden = NO;
                
                [_backBtn setTransform:CGAffineTransformIdentity];
                [_flashBtn setTransform:CGAffineTransformIdentity];
                [_guideBtn setTransform:CGAffineTransformIdentity];
                [_switchBtn setTransform:CGAffineTransformIdentity];
                [_rotateImageView setTransform:CGAffineTransformIdentity];
                [_guideLabel setTransform:CGAffineTransformIdentity];
                [_camaraLabel setTransform:CGAffineTransformIdentity];
                [_timeLabel setTransform:CGAffineTransformIdentity];
                
                break;
            case UIDeviceOrientationUnknown:
                
                break;
            default:
                
                break;
        }
    }
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if (self.editmode == NvSSVideoCreateScaleVertical) {
        self.timeLabel.center = self.view.center;
        self.timeLabel.top_LL = 64;
    }
}


- (void)focusGesture:(UITapGestureRecognizer*)gesture{
    CGPoint point = [gesture locationInView:self.liveWindow];
    CGFloat rectHalfWidth = self.focusView.frame.size.width / 2;
    if (point.x - rectHalfWidth < 0 || point.x + rectHalfWidth > self.liveWindow.frame.size.width || point.y - rectHalfWidth < 0 || point.y + rectHalfWidth > self.liveWindow.frame.size.height)
        return;
    
    self.focusView.center = point;
    [_context startAutoFocus:self.focusView.center];
    _focusView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
    }completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5 animations:^{
            _focusView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            _focusView.hidden = YES;
        }];
    }];
}

- (IBAction)backBtnPressed:(id)sender {
    [self closeFlash];
    [self dismissViewControllerAnimated:NO completion:nil];
}
- (IBAction)changeCamaraBtnPressed:(id)sender {
    if (_currentDeviceIndex == 0) {
        if (![_context startCapturePreview:1 videoResGrade:NvsVideoCaptureResolutionGradeHigh flags:0 aspectRatio:&_aspectRatio]) {
            NSLog(@"启动预览失败");
            return;
        }
        _currentDeviceIndex = 1;
        [_devicePositionChangeBtn setImage:[self imageFromBundle:@"cam_turnon"]forState:UIControlStateNormal];
        
    } else {
        if (![_context startCapturePreview:0 videoResGrade:NvsVideoCaptureResolutionGradeHigh flags:0 aspectRatio:&_aspectRatio]) {
            NSLog(@"启动预览失败");
            return;
        }
        
        [_devicePositionChangeBtn setImage:[self imageFromBundle:@"cam_turnoff"] forState:(UIControlStateNormal) ];
        
        _currentDeviceIndex = 0;
    }
}
- (IBAction)guideBtnPressed:(id)sender {
    if(_guideImageView.hidden)
    {
        _guideImageView.hidden = NO;
        [_guideBtn setImage:[self imageFromBundle:@"cam_guideon"] forState:UIControlStateNormal];
    }
    else
    {
        _guideImageView.hidden = YES;
        [_guideBtn setImage:[self imageFromBundle:@"cam_guideoff"] forState:UIControlStateNormal];
        
    }
}

- (IBAction)flashBtnPressed:(id)sender {
    if(_isflashOn)
    {
        _isflashOn = NO;
        [_flashBtn setImage:[self imageFromBundle:@"cam_flashoff"] forState:UIControlStateNormal];
    }
    else
    {
        _isflashOn = YES;
        [_flashBtn setImage:[self imageFromBundle:@"cam_flashon"] forState:UIControlStateNormal];
    }
    [_context toggleFlash:_isflashOn];
    
}



- (void)cameraDistrict {
    _isRecording = false;
    _currentDeviceIndex = 0;
    
    _context = [NvsStreamingContext sharedInstanceWithFlags:NvsStreamingContextFlag_Support4KEdit];
    
    if (!_context)
        return;
    
    if ([_context captureDeviceCount] == 0) {
        [self showAlert:@"没有可用于采集的设备"];
        return;
    }
    
    if (![_context connectCapturePreviewWithLiveWindow:self.liveWindow]) {
        [self showAlert:@"连接预览窗口失败"];
        return;
    }
    
    if (![_context startCapturePreview:0 videoResGrade:NvsVideoCaptureResolutionGradeHigh flags:0 aspectRatio:nil]) {
        [self showAlert:@"启动预览失败"];
        return;
    }
    if ([_context captureDeviceCount] > 1)
        [self.devicePositionChangeBtn setEnabled:YES];
    
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *outputFilePath = [docPath stringByAppendingFormat:@"/%@.mov",[Utils getTimeAndRandom]];

    self.videoUrl = outputFilePath;
    _enableRotation=YES;
    _guideImageView.hidden = YES;
    [self.view bringSubviewToFront:_sureBtn];
    [self.view bringSubviewToFront:_cancelBtn];
    [self.view bringSubviewToFront:_navView];
    [self.view bringSubviewToFront:_guideImageView];
    [self.view bringSubviewToFront:_timeLabel];
    [self.view bringSubviewToFront:_rotateImageView];
    [self.view bringSubviewToFront:_guideLabel];
    [self.view bringSubviewToFront:_recordBtn];
}


- (void)showAlert:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Tips" message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * action) {
                                                       [self dismissViewControllerAnimated:YES completion:nil];
                                                   }];
    
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:nil];
}

//MARK:预览
- (void)finishRecord{
    [_context stopRecording];
    [self removeCurrentTimer];
    _isRecording = false;
    _recordBtn.hidden = YES;
    [self saveVideoToDocument];
}

- (void)ensureStartPreview {
    if(_isNeedRestartPreview) {
        if (![_context startCapturePreview:_currentDeviceIndex videoResGrade:NvsVideoCaptureResolutionGradeHigh flags:0 aspectRatio:nil]) {
            [self showAlert:@"启动预览失败"];
            return;
        }
        _isNeedRestartPreview = NO;
    }
}

- (IBAction)recordBtnPressed:(id)sender {
    if (_isRecording) {
        [self finishRecord];
        return;
    }
    _navView.hidden = YES;
    _enableRotation = NO;
    if ([[NSFileManager defaultManager] fileExistsAtPath:self.videoUrl]) {
        NSError *error;
        if (![[NSFileManager defaultManager] removeItemAtPath:self.videoUrl error:&error]) {
            NSLog(@"removeItemAtPath failed, error: %@", error);
            return;
        }
    }
    [self ensureStartPreview];
    if (![_context startRecording:self.videoUrl]) {
        [self showAlert:@"启动预览失败"];
        return;
    }
    [self addCurrentTimer];
    [_recordBtn setImage:[self imageFromBundle:@"cam_recording"] forState:UIControlStateNormal];
    _isRecording = true;
    _sureBtn.hidden = YES;
    _cancelBtn.hidden = YES;
    _recordBtn.hidden = NO;
    
}
- (void)closeFlash {
    if(_isflashOn) {
        [_flashBtn setImage:[self imageFromBundle:@"cam_flashoff"] forState:UIControlStateNormal];
        [_context toggleFlash:NO];
    }
}
- (IBAction)sureBtnPressed:(id)sender {
    //视频录入完成之后在后台将视频存储到相簿
    
    [self closeFlash];
    _enableRotation=YES;
    
    _sureBtn.hidden = YES;
    _cancelBtn.hidden = YES;
    _recordBtn.hidden = NO;
    _navView.hidden = NO;
    [self saveVideoToDocument];
    [self dismissViewControllerAnimated:NO completion:^(){
        if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didFinishTakeVideo:)] ==YES) {
            [self.delegate didFinishTakeVideo:_videoAsset];
        }
    }];
   

}
//MARK:保存视频
- (void)saveVideoToDocument {
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalQueue, ^(void) {
        NSMutableArray *videoIds = [NSMutableArray array];
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                    
                    PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL fileURLWithPath:self.videoUrl]];
                    [videoIds addObject:req.placeholderForCreatedAsset.localIdentifier];
                    
                    
                } completionHandler:^(BOOL success, NSError * _Nullable error) {
                    
                    NSLog(@"success = %d, error = %@", success, error);
                    
                    if (success) {
                        PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:videoIds options:nil];
                        [result enumerateObjectsUsingBlock:^(PHAsset * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            
                            _videoAsset = obj;
                            *stop = YES;
                        }];
                    }
                    dispatch_semaphore_signal(sema);
                }];
            } else {
                //没有授权
                dispatch_semaphore_signal(sema);
            }
        }];
        
        
    });
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    NSLog(@"保存完了");
    NvTakeVideoViewController __weak *weakSelf = self;
    [[PHCachingImageManager new] requestAVAssetForVideo:_videoAsset
                                      options:[PHVideoRequestOptions new] resultHandler:^(AVAsset * avasset, AVAudioMix * audioMix, NSDictionary * info) {
                                          dispatch_async(dispatch_get_main_queue(), ^{
                                              [weakSelf setAssetUrlForEditingClipModel:avasset];
                                          });
                                      }];
}

- (void)setAssetUrlForEditingClipModel:(AVAsset *) asset{
    preViewController = [[TakeVideoPreViewController alloc] init];
    preViewController.delegate = self;
    
    MediaModel *model = [[MediaModel alloc] init];
    self.clipModel.clipPath = _videoUrl;
    self.clipModel.modelType = NvMakeFilmClipModelAdded;
    self.clipModel.clipType = NvClipVideo;
    model.modelArray = @[self.clipModel];
    preViewController.model = model;
    preViewController.totalTime = [self stringWithTime:self.time-1];
    
    [self presentViewController:preViewController animated:YES completion:nil];
}

- (IBAction)cancelBtnPressed:(id)sender {
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    BOOL bRet = [fileMgr fileExistsAtPath:self.videoUrl];
    if (bRet) {
        NSError *err;
        [fileMgr removeItemAtPath:self.videoUrl error:&err];
    }
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    self.videoUrl = [NSString stringWithFormat:@"%@/%@record.mov",path,[Utils getTimeAndRandom]];
    
    [_recordBtn setImage:[self imageFromBundle:@"cam_record"] forState:UIControlStateNormal];
    _enableRotation = YES;
    _sureBtn.hidden = YES;
    _cancelBtn.hidden = YES;
    _recordBtn.hidden = NO;
    _navView.hidden = NO;
    self.time = 0;
    _timeLabel.text = [self stringWithTime:self.time];
    [self ensureStartPreview];
}

- (NSString *)stringWithTime:(NSTimeInterval)time {
    int minute = time / 60;
    int second = (int)time % 60;
    return [NSString stringWithFormat:@"%02d:%02d",minute, second];
}

/**
 *  添加定时器
 */
- (void)addCurrentTimer {
    //在新增定时器之前，先移除之前的定时器
    [self removeCurrentTimer];
    
    [self updateCurrentTimer];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCurrentTimer) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

/**
 *  移除定时器
 */
- (void)removeCurrentTimer {
    [self.timer invalidate];
    self.timer = nil;
}

/**
 *  触发定时器
 */
- (void)updateCurrentTimer {
    
    _timeLabel.text = [self stringWithTime:self.time];
    self.time++;
}

//视频保存后的回调
//2017年4月1日的时候发现这个方法好像没有被调用也不敢删除
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error{
    if (error) {
        NSLog(@"保存视频过程中发生错误，错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"视频保存成功.");
    }
}

//MARK:TakeVideoPreViewControllerDelegate
- (void)takeVideoPreViewController:(TakeVideoPreViewController *)preController cancelClick:(UIButton *)cancelButton {
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest deleteAssets:@[_videoAsset]];
        [[NSFileManager defaultManager]removeItemAtPath:self.videoUrl error:nil];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            //需要重新录制要重新启用预览
            _isNeedRestartPreview = YES;
            [self cancelBtnPressed:nil];
        });
    }];
}
- (void)takeVideoPreViewController:(TakeVideoPreViewController *)preController okClick:(UIButton *)okButton {
    [self closeFlash];
    [self dismissViewControllerAnimated:YES completion:^(){
        if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didFinishTakeVideo:)] ==YES) {
            [self.delegate didFinishTakeVideo:_videoAsset];
        }
    }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"录制页面消失");
}

- (UIImage *)imageFromBundle:(NSString*)imageName {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    NSString *imagePath = [myBundle pathForResource:imageName ofType:@"png"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    return image;
}

@end
